<template>
    <div>
        
        <el-form  :model="addVideo"  class="demo-form-inline">

            <el-form-item label="年级:" :label-width="formLabelWidth">
                <el-select v-model="addVideo.grade" placeholder="请选择"  @change="grada">
                  <el-option
                    v-for="item in grade"
                    :value="item.dictValue" 
                    :key="item.dictValue"             
                    :label="item.dictLabel">
                  </el-option>
                </el-select>
            </el-form-item>


            <el-form-item label="学科:" :label-width="formLabelWidth">
                <el-select v-model="addVideo.discipline" placeholder="请选择" @change="subject">
                  <el-option                 
                    v-for="item in findData"
                    :value="item.id" 
                    :key="item.id"             
                    :label="item.subject"
                    >
                  </el-option >
                </el-select>              
            </el-form-item>

            <el-form-item label="名称:" :label-width="formLabelWidth">
              <el-input v-model="addVideo.videoName"></el-input>
            </el-form-item>

            <el-form-item label="封面:" :label-width="formLabelWidth" >
                <div class="imge">
                    <div class="but">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/upload"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                            :headers="uploadHeaders"
                            >
                            <el-button type="success" size="medium" >上传图片</el-button> 
                           
                        </el-upload>
                        
                    </div>
                    <div class="block">
                      <el-image :src="this.addVideo.videoImg"  style="width: 300px; height: 220px;"></el-image>
                    </div>
                </div>
                
            </el-form-item>

            <el-form-item label="视频:" :label-width="formLabelWidth" >
                <div class="vide">
                    <div class="but">
                        <el-upload
                          class="upload-demo"
                          
                          action="/api/upload"
                          :on-success="handleSuccess"
                          :on-error="handleError"
                          :before-upload="beforeUpload"
                          :file-list="fileList"
                          :headers="uploadHeaders"
                          multiple>
                          <el-button type="success" size="medium" >上传视频</el-button> 
                        </el-upload>

                    </div>
                    <div class="block">
                        <video :src="addVideo.video" controls style="width: 100%; height: auto;"></video>
                    </div>
                    
                </div>

               
            </el-form-item>

            <el-form-item label="试卷:" :label-width="formLabelWidth">
                <el-button type="success" size="medium" @click="openDialog()" style="margin-left: 20px;">选择试卷</el-button> {{ this.testName }}

            </el-form-item>



        </el-form>

        <div slot="footer" class="dialog-footer" style="margin-left: 130px;">
          <el-button type="primary" size="medium" v-if="this.id==null" @click="add()">提 交</el-button>
          <el-button type="primary" size="medium" v-else @click="upDate()">提 交</el-button>

          <el-button  @click="reset()" size="medium">重 置</el-button>
        </div>

        <!-- 打开试卷列表 -->

        <el-dialog title="试卷列表" :visible.sync="dialogTableVisible" >

        <!-- 条件查询 -->
        <el-row>
            <el-col :span="24"><div class="grid-content bg-purple-dark">
                <el-form :inline="true" :model="searchData"  class="demo-form-inline">

                  <el-form-item label="ID">
                    <el-input v-model="searchData.id" clearable></el-input>
                  </el-form-item>

                    <el-button type="primary" @click="search">查询</el-button>

                </el-form>

                
                </div></el-col>
          </el-row>

        <el-table :data="testList" height="240" border @selection-change="handleSelectionChange">
        <!-- 批量 -->
        <el-table-column type="selection" width="55"></el-table-column>

          <el-table-column prop="id" label="Id" width="100"></el-table-column>
         <el-table-column  label="学科" width="220">
             <template slot-scope="scope">
              {{ scope.row.disc }}(
                 <span v-if="scope.row.grad ==0">一年级</span>
                 <span v-if="scope.row.grad ==1">二年级</span>
                 <span v-if="scope.row.grad ==2">三年级</span>
                 <span v-if="scope.row.grad ==3">四年级</span>
                 <span v-if="scope.row.grad ==4">五年级</span>
                 <span v-if="scope.row.grad ==5">六年级</span>
                 <span v-if="scope.row.grad ==6">初一</span>
                 <span v-if="scope.row.grad ==7">初二</span>
                 <span v-if="scope.row.grad ==8">初三</span>
                 <span v-if="scope.row.grad ==9">高一</span>
                 <span v-if="scope.row.grad ==10">高二</span>
                 <span v-if="scope.row.grad ==11">高三</span>
              )
             </template>

         </el-table-column>

         <el-table-column prop="testName" label="名称" width="200"></el-table-column>
         <el-table-column prop="createTime" label="创建时间"></el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
         <el-button @click="dialogTableVisible=false">取 消</el-button>
         <el-button  type="primary" @click="Addtest()">确 定</el-button>

        </div>

        <!-- 分页 -->
        <div class="block">
         <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="pageNum"
         :page-sizes="[2, 4, 6, 8]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total" style="float:right">
         </el-pagination>
        </div>


        </el-dialog>

    </div>
</template>

<script>
import { getToken } from '@/util/auth';
import axios from 'axios';

export default {
    data(){
       return{
        uploadHeaders:{"Authorization": getToken()}, //获取登录值

            id:'',
            formLabelWidth: '120px', //新增表单宽度
            dialogTableVisible: false, //新增弹窗
            grade:[],
            findData:[],
            fileList:[],
            addVideo:{
                "createTime": "",
                "discipline": "",
                "grade": "",
                "id": 0,
                "paper": "",
                "subjectId": "",
                "video": "",
                "videoImg": "",
                "videoName": "",
                testData:[]
            },
            testData:[],
            testList:[],
            searchData:{
                id:''
            },
            pageNum:1,
            pageSize:4,
            total:null,
            val:'',
            testName:'',
            subId:''
       }
    },
    created(){
        this.searchDict()
        this.id = sessionStorage.getItem("id");
        if(this.id){
          this.getVideo()
        }
    },
    methods:{
        //
        upDate(){
            this.addVideo.testData =  this.testData
            axios.put("/api/video/updateVideo",this.addVideo).then(res=>{
              //弹框
              this.$message({
                         message: res.data.message,
                         type: 'success'
                       });
            })
            this.$router.push("/tt")
        },

        //回显
        getVideo(){
            axios.get("/api/video/findVideoById?id="+this.id).then(res=>{
              this.addVideo = res.data.data
              console.log("111:", this.addVideo);
              // this.searchDict()
              console.log("addTask:", res.data.data.testData);
              this.testName =  res.data.data.testData.map(item => item.testName).join(",")
              this.subId = res.data.data.grade
              this.Subjec() 

            })
            sessionStorage.removeItem("id")
        },
        //新增
        add(){
            console.log("数据",this.addVideo);
            this.addVideo.testData =  this.testData
            axios.post("/api/video/addVideo",this.addVideo).then(res=>{
              //弹框
              this.$message({
                         message: res.data.message,
                         type: 'success'
                       });
            })
            this.$router.push("/tt")
        },
        subject(val){
            this.addVideo.subjectId = val
        },
        //确认添加试卷
        Addtest(){
            this.testData.push(...this.val)
            this.dialogTableVisible = false
        },
        //多选框添加试卷
        handleSelectionChange(val){
            console.log("试卷信息",val);
             console.log("试卷信息aaa", ...val);
            this.val = val
            this.testName = val.map(item => item.testName).join(",")
        },
        //打开列表弹框
        openDialog(){
            this.dialogTableVisible = true
            this.initTab()
        },

        //试卷列表
        initTab(){
            axios.post("/api/test/findTbTestPaginationList?pageNum=" + this.pageNum + "&pageSize=" +this.pageSize,this.searchData).then(res=>{
                this.testList = res.data.data.items
                this.total = res.data.data.totalElements 
            })
        },
        search(){
            this.initTab()
        },

        //分页
         handleSizeChange(val) {
          this.pageSize = val;
          console.log(`每页 ${val} 条`);
          this.initTable();
        },
        handleCurrentChange(val) {
          this.pageNum = val;
          console.log(`当前页: ${val}`);
           this.initTable()
        },
        //判断学科
        grada(val){
            this.subId = val  
            this.Subjec()            
        },
        //学科
        Subjec(){
            axios.get("/api/subject/SubjectList?id="+this.subId).then(res=>{
                this.findData = res.data.data
            })
        },
        //重置
        reset(){
            this.addVideo={}
            this.addVideo.video=''
            this.testName=''
        },
        //年级
        searchDict(){
            axios.get("/api/dict/findDictDataByDictTypeIdSysUserSex?dictType=sys_grade_status").then(res=>{
            this.grade =res.data.data
            })
        },
        //图片上传
        handleAvatarSuccess(res, file) {

        this.addVideo.videoImg = file.response.data
        console.log('aaa',file.response);
        
        this.code = true;
        console.log("sasas",this.addVideo.videoImg)

        },
        beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
        },
        
        //视频上传
        handleSuccess(response, file, fileList) {
          this.addVideo.video=file.response.data;
          // 处理上传成功逻辑
          console.log('Success:', response, file, fileList);
          this.fileList = fileList;
        //   this.codec = true; // 更新视频源
        },
        handleError(err, file, fileList) {
          // 处理上传错误逻辑
          console.error('Error:', err, file, fileList);
          this.$message.error('上传失败: ' + err.message);
        },
        beforeUpload(file) {
          // 检查文件类型和大小
          const isVideo = ['video/mp4', 'video/flv', 'video/avi'].includes(file.type);
          const isLt150M = file.size / 1024 / 1024 < 150;


          if (!isVideo) {
            this.$message.error('只能上传mp4/flv/avi等视频文件');
          }
          if (!isLt150M) {
            this.$message.error('视频大小不能超过150MB');
          }


          return isVideo && isLt150M;
        },
    }
}
</script>
<style scoped>

.imge{
    width: 700px;
    height: 220px;
    /* background-color: #a24343; */
    display:flex;
}

.imge .but{
   width: 100px;
   height: 50px;
   /* background-color: #1ead8c; */
   margin-left: 30px;
   margin-top: 100px;
}

.imge .block{
    width: 300px;
    height: 220px;
    /* background-color: #2a23a2; */
    margin-left: 30px;
    }
.vide{
    width: 100%;
    height: auto;
    /* background-color: #a24343; */
    display:flex;
}

.vide .but{
   width: 100px;
   height: 50px;
   /* background-color: #1ead8c; */
   margin-left: 30px;
   margin-top: 70px;
}

.vide .block{
    width: auto;
    height: auto;
    /* background-color: #2a23a2; */
    margin-left: 30px;
    margin-top: 10px;
    }



</style>